package com.xinlianshiye.im.websocket;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
public class WebSocketRequestMappingInfo {

    private String url;

    private static final Map<String, WebSocketRequestMappingInfo> mappingInfoMap = new HashMap<>();

    private WebSocketRequestMappingInfo(String url) {
        this.url = url;
    }

    /**
     * 向注册表中注册 MappingInfo
     * */
    public static void registerMappingInfo(WebSocketRequestMappingInfo mappingInfo) {
        if (findMappingInfo(mappingInfo.getUrl()) != null) {
            log.error("MappingInfo[url: {}] 出现了冲突", mappingInfo.getUrl());
        }
        mappingInfoMap.put(mappingInfo.getUrl(), mappingInfo);
    }

    /**
     * 从注册表中查找符合条件的 MappingInfo
     * 如果符合条件的 MappingInfo 不存在则返回 null
     * */
    public static WebSocketRequestMappingInfo findMappingInfo(String url) {
        if (mappingInfoMap.containsKey(url)) {
            return mappingInfoMap.get(url);
        }
        return null;
    }

    public static WebSocketRequestMappingInfo createRequestMappingInfo(Method element) {
        WebSocketRequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, WebSocketRequestMapping.class);
        return (requestMapping != null ? createRequestMappingInfo(requestMapping) : null);
    }

    private static WebSocketRequestMappingInfo createRequestMappingInfo(WebSocketRequestMapping requestMapping) {
        WebSocketRequestMappingInfo mappingInfo = findMappingInfo(requestMapping.value());
        return mappingInfo != null ? mappingInfo : new WebSocketRequestMappingInfo(requestMapping.value());
    }
}
